#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Kitten TTS 前后端分离系统演示脚本

本脚本展示了如何使用分离的前端和后端服务进行语音合成。
使用前请确保后端API服务和前端应用已正确启动。
"""

import os
import sys
import time
import requests
import logging
from urllib.parse import urljoin

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

class KittenTTSClient:
    def __init__(self, api_base_url="http://localhost:8000"):
        """初始化Kitten TTS客户端
        
        Args:
            api_base_url: 后端API服务的基础URL
        """
        self.api_base_url = api_base_url
        self.session = requests.Session()
        
    def test_connection(self):
        """测试与后端API服务的连接"""
        try:
            url = urljoin(self.api_base_url, "/")
            response = self.session.get(url, timeout=5)
            response.raise_for_status()
            data = response.json()
            logger.info(f"成功连接到后端API服务: {data['message']}")
            logger.info(f"API版本: {data.get('version', '未知')}")
            logger.info(f"可用端点: {', '.join(data.get('endpoints', []))}")
            return True
        except Exception as e:
            logger.error(f"连接后端API服务失败: {e}")
            logger.error("请确保后端服务已启动并监听在正确的端口上")
            return False
    
    def get_languages(self):
        """获取支持的语言列表"""
        try:
            url = urljoin(self.api_base_url, "/api/languages")
            response = self.session.get(url, timeout=10)
            response.raise_for_status()
            data = response.json()
            languages = data.get('languages', [])
            logger.info(f"支持的语言: {', '.join(languages)}")
            return languages
        except Exception as e:
            logger.error(f"获取语言列表失败: {e}")
            return []
    
    def get_voices(self, language="en-us"):
        """获取指定语言支持的语音列表"""
        try:
            url = urljoin(self.api_base_url, f"/api/voices?language={language}")
            response = self.session.get(url, timeout=10)
            response.raise_for_status()
            data = response.json()
            voices = data.get('voices', [])
            logger.info(f"语言 '{language}' 支持的语音: {', '.join(voices)}")
            return voices
        except Exception as e:
            logger.error(f"获取语音列表失败: {e}")
            return []
    
    def generate_tts(self, text, voice="expr-voice-5-m", speed=1.0, language="en-us", output_file="output.wav"):
        """生成语音并保存到文件"""
        try:
            url = urljoin(self.api_base_url, "/api/tts")
            payload = {
                "text": text,
                "voice": voice,
                "speed": speed,
                "language": language
            }
            
            logger.info(f"开始生成语音，文本: '{text[:30]}...'，语音: {voice}，语速: {speed}，语言: {language}")
            start_time = time.time()
            response = self.session.post(url, json=payload, timeout=60)
            response.raise_for_status()
            
            # 保存音频文件
            with open(output_file, "wb") as f:
                f.write(response.content)
            
            process_time = time.time() - start_time
            logger.info(f"语音生成成功，耗时: {process_time:.2f}秒")
            logger.info(f"音频文件已保存到: {os.path.abspath(output_file)}")
            return True
        except requests.exceptions.HTTPError as e:
            logger.error(f"HTTP错误: {e}")
            if e.response and e.response.content:
                try:
                    error_data = e.response.json()
                    logger.error(f"错误详情: {error_data}")
                except:
                    logger.error(f"错误响应: {e.response.content}")
            return False
        except Exception as e:
            logger.error(f"语音生成失败: {e}")
            return False

    def run_full_demo(self):
        """运行完整的演示流程"""
        logger.info("===== Kitten TTS 前后端分离系统演示开始 =====")
        
        # 1. 测试连接
        if not self.test_connection():
            logger.error("演示终止，无法连接到后端服务")
            return False
        
        # 2. 获取语言列表
        languages = self.get_languages()
        if not languages:
            logger.warning("无法获取语言列表，使用默认语言")
            languages = ["en-us", "zh"]
        
        # 3. 对每种语言进行测试
        test_texts = {
            "en-us": "Hello, this is a test of Kitten TTS system.",
            "zh": "你好，这是Kitten TTS系统的测试。"
        }
        
        for lang in languages:
            # 获取该语言支持的语音
            voices = self.get_voices(lang)
            if not voices:
                logger.warning(f"没有获取到语言 '{lang}' 支持的语音，使用默认语音")
                voices = ["expr-voice-5-m"]
            
            # 选择第一个语音进行测试
            voice = voices[0]
            
            # 获取测试文本
            text = test_texts.get(lang, f"This is a test for language {lang}.")
            
            # 生成语音
            output_file = f"demo_output_{lang}_{voice.replace('-', '_')}.wav"
            self.generate_tts(text, voice, speed=1.0, language=lang, output_file=output_file)
        
        logger.info("===== Kitten TTS 前后端分离系统演示结束 =====")
        logger.info("请确保同时启动前端Vue应用体验完整功能")
        logger.info("前端访问地址: http://localhost:3000")
        return True

if __name__ == "__main__":
    # 创建客户端实例
    client = KittenTTSClient()
    
    # 运行完整演示
    client.run_full_demo()
    
    # 提示用户如何启动前端
    print("\n前端应用启动方法：")
    print("1. 打开新的命令行窗口")
    print("2. 进入前端目录: cd kitten_tts_frontend")
    print("3. 安装依赖: npm install")
    print("4. 启动开发服务器: npm run dev")
    print("\n然后在浏览器中访问: http://localhost:3000")
    print("\n注意：确保后端API服务和前端应用同时运行")